import React from 'react';
import { useRequest } from 'umi';
import {
  getCompanyID,
  getTenantID,
  getUserDepID,
  requestFunCompon,
} from '@/utils';

export const usePositionTreeData = (
  onTreeSelectChange: (id: string) => any,
  curRes: Record<any, any>,
) => {
  /* 获取左边树的数据 */
  const orgTree = useRequest(
    () => {
      if (curRes['/positionController/getTreeByCompany']) {
        let bodyParams = {
          companyID: getCompanyID(),
          dicTypeIds: `${getTenantID()}1003`,
        };
        return requestFunCompon(
          'POST',
          '/positionController/getTreeByCompany',
          bodyParams,
        );
      } else if (curRes['/positionController/getTreeByDepart']) {
        let bodyParams = {
          id: getUserDepID(),
          dicTypeIds: `${getTenantID()}1003`,
        };
        return requestFunCompon(
          'POST',
          '/positionController/getTreeByDepart',
          bodyParams,
        );
      }
    },
    {
      manual: false, //页面初始请求为true
      onSuccess: (res) => {
        if (res && res?.msgFlag) {
          onTreeSelectChange(res?.obj?.id);
        }
      },
    },
  );

  let orgTreeData = React.useMemo(() => {
    if (orgTree?.data?.msgFlag) {
      return [orgTree?.data?.obj];
    } else {
      return [];
    }
  }, [orgTree.data]);

  return {
    orgTreeData: orgTreeData,
    treeLoading: orgTree.loading,
    getTreeData: orgTree.run,
  };
};
